// pages/match/match.js
var match = require('../../utils/match');
Page({
    uploadImage(){
       var matchid = this.data.matchid;
       var index = this.data.index;
       var image = null;
       var time = new Date();
       var userid = this.data.userid;
       var username = this.data.username;
       
        var that = this
        wx.chooseMedia({
                count: 1,
                success(res) {
                        console.log(res.tempFiles)
                        console.log(userid)
                        var po = res.tempFiles[0].tempFilePath.lastIndexOf(".")
                        var ext = res.tempFiles[0].tempFilePath.slice(po)
                        wx.cloud.uploadFile({
                                cloudPath: matchid+userid+index + ext,
                                filePath: res.tempFiles[0].tempFilePath,
                                success(res) {
                                    console.log(res.fileID)
                                    image = res.fileID;
                                    var database = wx.cloud.database();
                                    database.collection("itemScore").add({
                                       data:{
                                           matchid:matchid,
                                           index:index,
                                           image:image,
                                           time:time,
                                           userid:userid,
                                           username:username
                                       }
                                    }).then((res)=>{
                                      if(res){
                                        wx.showToast({
                                          title: '图片上传成功',
                                        });
                                      //判断是否完成了整个比赛
                                      database.collection("itemScore").where({
                                         userid:that.data.userid,
                                         matchid:that.data.matchid
                                      }).get().then((b)=>{
                                        //用户分段完赛记录数量等于当前比赛的图片数组长度
                                         if(b.data.length==that.data.imageList.length){
                                         var matchid = that.data.matchid;
                                         var matchname= that.data.matchname;
                                         var userid = that.data.userid;
                                         var username= that.data.username;
                                         database.collection("finalScore").where({
                                           matchid:matchid
                                         }).get().then((c)=>{
                                             var len= c.data.length;
                                             var mingci= len+1;
                                             //获取完赛分段的所有时间的最晚时间
                                             database.collection("itemScore").where({
                                                matchid:matchid,
                                                userid:userid
                                             }).get().then((d)=>{
                                                var time = d.data[0].time;
                                                for (let i=0;i<d.data.length;i++){
                                                     if(d.data[i].time>time){
                                                       time=d.data[i].time;
                                                     }
                                                }
                                                //console.log(that.data.matchid)
                                                database.collection("match").where({
                                                   userid:that.data.userid
                                                }).get().then((e)=>{
                                                console.log(e);
                                                   matchname=e.data[0].matchname;
                                                   var beginTime= e.data[0].beginTime;
                                                   var sjc =time.getTime()-beginTime.getTime();
                                                   var hours=Math.floor(sjc/(1000*60*60));
                                                   var fenzhong =Math.floor(sjc%(1000*60*60)/(60000));
                                                   var sec= Math.floor(sjc%(60000)/1000);
                                                   var zhong= hours+"小时"+fenzhong+"分钟"+sec+"秒";
                                                   database.collection("finalScore").add({
                                                      data:{
                                                        matchid:matchid,
                                                        matchname:matchname,
                                                        userid:userid,
                                                        username:username,
                                                        mingci:"第"+mingci+"名",
                                                        sjc:sjc,
                                                        zhong:zhong
                                                      }
                                                   }).then((f)=>{
                                                      if(f)wx.showToast({
                                                        title: '比赛完成了,你获得了第'+mingci+"名，比赛用时"+zhong,
                                                      })
                                                      //判断当前是否为完成比赛的最后一个人，全加起来为一个小组
                                                      
                                                   });
                                                })
                                             });
                                         });
                                         }
                                      })
                                      }else{
                                        wx.showToast({
                                          title: '图片上传失败',
                                        })
                                      }
                                    }).catch((err)=>{
                                      wx.showToast({
                                        title: '图片上传异常',
                                      });
                                      console.log(err);
                                    });
                                    that.setData({
                                      currentImage:res.fileID
                                    });
                                }
                        })
                }
        })
    },

    click:function(e){
        this.setData({
            index : e.currentTarget.id
        });
        //查询数据库，获取切换分段后的完赛选手
        var that = this;
        var database=wx.cloud.database();
        database.collection("itemScore").where({
          matchid:that.data.matchid,
          index:that.data.index+""
        }).get().then((res)=>{
          for(let i=0;i<res.data.length;i++){
            var time = res.data[i].time;
            var d = time.toLocaleDateString().substring(0,10);
            var t = time.toTimeString().substring(0,8);
            time = d+" "+t;
            res.data[i].time=time;
          }
          that.setData({
            itemScore:res.data
          });
        })
        //判断当前用户比赛是否完成
        database.collection("itemScore").where({
          userid:that.data.userid,
          matchid:that.data.matchid,
          index:that.data.index+"",
        }).get().then((a)=>{
          if(a.data.length>0){
            that.setData({
              isWancheng:false
            })
          }else{
            that.setData({
              isWancheng:true
            });
          }
        });
    },
    daoda(){
      var k = this.data.index;
        this.setData({
          dialogShow:true,
          currentImage:this.data.imageList[k]
        });
    },
    /**
     * 页面的初始数据
     */
    data: {
        isWancheng:true,
        times:[],
        itemScore:[],
        currentImage:null,
        userid:null,
        username:null,
        matchid:null,
        title:null,
        imageList:[],
        picnames:[],
        index:0,
        category: 0,
        dialogShow:false,
        id: null,
        matches:match.list,
        little_location: "https://lbs.gtimg.com/visual/miniprogram-plugin/route-planning/assets/route_end.png"
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        //获取用户id
        var that = this;
        wx.getStorage({
            key:"user",
            success(res){
                that.setData({
                    userid:res.data.id
                });
                var database = wx.cloud.database();
                database.collection("user").where({
                    _id:that.data.userid
                }).get().then((r)=>{
                    that.setData({
                      username:r.data[0].name
                    });
                })
                database.collection("baoming").where({
                    userid: res.data.id
                }).get().then((msg)=>{
                    that.setData({
                        matchid:msg.data[0].matchid,
                        title:msg.data[0].title,
                    });
                    wx.setNavigationBarTitle({
                      title: msg.data[0].title,
                    });
                    //判断当前用户比赛是否完成
                    database.collection("itemScore").where({
                      userid:that.data.userid,
                      matchid:that.data.matchid,
                      index:0+"",
                    }).get().then((a)=>{
                      if(a.data.length>0){
                        that.setData({
                          isWancheng:false
                        })
                      }else{
                        that.setData({
                          isWancheng:true
                        });
                      }
                    });
                    //获取该比赛的对应图片
                    console.log(that.data.userid);
                    database.collection("match").where({
                        userid: that.data.userid
                    }).get().then((m)=>{
                        console.log(m);
                        that.setData({
                            imageList:m.data[0].imageList
                        });
                        var picnames = [];
                        for(let i = 0;i < that.data.imageList.length;i++){
                            var loc = that.data.imageList[i].lastIndexOf("/");
                            var picname = that.data.imageList[i].slice(loc + 1);
                            loc = picname.lastIndexOf(".");
                            picname = picname.slice(0,loc);
                            picnames.push(picname);
                        }
                        that.setData({
                            picnames:picnames
                        });
                    });
                    //当前已经完成景点的人员数组
                    database.collection("itemScore").where({
                      matchid:that.data.matchid,
                      index:that.data.index+""

                    }).get().then((s)=>{
                      //console.log("成绩的长度"+s.data.length)
                       that.setData({
                         itemScore:s.data
                       });
                       //时间显示出来
                       var times = [];
                       for (let i = 0;i<that.data.itemScore.length;i++){
                          var data = that.data.itemScore[i];
                          var time = data.time;
                          
                          var t = time.toTimeString().substring(0,5);
                          var d = time.toLocaleDateString().substring(0,10);
                          time = d+" "+t
                          that.data.itemScore[i].time=time;
                          
                       }
                       that.setData({
                         itemScore:that.data.itemScore
                       });
                    })
                });
            }
        })
    },
})